package com.cardcaptorsakura.service.output;

import com.cardcaptorsakura.model.dto.ChatRequest;
import com.cardcaptorsakura.model.dto.ChatResponse;
import com.cardcaptorsakura.model.entity.PersonaConfig;
import com.cardcaptorsakura.service.persona.PersonaService;
import com.cardcaptorsakura.service.memory.MemoryService;
import com.cardcaptorsakura.config.AIConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 文本生成服务
 * 负责根据人格配置和用户输入生成个性化文本响应
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TextGenerationService {

    private final ChatClient chatClient;
    private final PersonaService personaService;
    private final MemoryService memoryService;
    private final AIConfig aiConfig;

    /**
     * 生成文本响应
     *
     * @param request 聊天请求
     * @return 生成的文本内容
     */
    public String generateText(ChatRequest request) {
        try {
            // 1. 获取当前人格配置
            PersonaConfig persona = personaService.getActivePersona(request.getUserId());
            
            // 2. 构建系统提示词
            String systemPrompt = buildSystemPrompt(persona, request);
            
            // 3. 获取相关记忆上下文
            List<String> memories = getRelevantMemories(request);
            
            // 4. 构建完整的提示词
            List<Message> messages = buildMessages(systemPrompt, request.getText(), memories);
            
            // 5. 调用AI模型生成响应
            Prompt prompt = new Prompt(messages);
            String response = chatClient.call(prompt).getResult().getOutput().getContent();
            
            log.info("Generated text response for user: {}, persona: {}", 
                    request.getUserId(), persona.getId());
            
            return response;
            
        } catch (Exception e) {
            log.error("Error generating text response for user: {}", request.getUserId(), e);
            return generateFallbackResponse(request);
        }
    }

    /**
     * 构建系统提示词
     */
    private String buildSystemPrompt(PersonaConfig persona, ChatRequest request) {
        StringBuilder promptBuilder = new StringBuilder();
        
        // 基础人格设定
        promptBuilder.append("你是").append(persona.getName())
                    .append("，").append(persona.getDescription()).append("。\n");
        
        // 人格特质参数
        Map<String, Object> traits = persona.getTraits();
        if (traits != null) {
            if (traits.containsKey("humorLevel")) {
                double humorLevel = (Double) traits.get("humorLevel");
                if (humorLevel > 0.7) {
                    promptBuilder.append("你的回答应该幽默风趣。\n");
                } else if (humorLevel < 0.3) {
                    promptBuilder.append("你的回答应该严肃专业。\n");
                }
            }
            
            if (traits.containsKey("empathyLevel")) {
                double empathyLevel = (Double) traits.get("empathyLevel");
                if (empathyLevel > 0.7) {
                    promptBuilder.append("你应该表现出高度的同理心和关怀。\n");
                }
            }
        }
        
        // 根据人格类型添加专业指导
        switch (persona.getId()) {
            case "doctor":
                promptBuilder.append("请提供专业的医疗建议，但要提醒用户这不能替代专业医生的诊断。\n");
                break;
            case "chef":
                promptBuilder.append("请提供创意的烹饪建议和食谱，考虑营养搭配和口味偏好。\n");
                break;
            case "companion":
                promptBuilder.append("请提供情感支持和陪伴，倾听用户的感受并给予温暖的回应。\n");
                break;
        }
        
        // 输出格式要求
        promptBuilder.append("请用中文回答，语言自然流畅，符合你的人格特点。");
        
        return promptBuilder.toString();
    }

    /**
     * 获取相关记忆
     */
    private List<String> getRelevantMemories(ChatRequest request) {
        if (!request.getOptions().isUseMemory()) {
            return new ArrayList<>();
        }
        
        try {
            return memoryService.searchRelevantMemories(
                request.getUserId(), 
                request.getText(), 
                5 // 最多返回5条相关记忆
            );
        } catch (Exception e) {
            log.warn("Failed to retrieve memories for user: {}", request.getUserId(), e);
            return new ArrayList<>();
        }
    }

    /**
     * 构建消息列表
     */
    private List<Message> buildMessages(String systemPrompt, String userText, List<String> memories) {
        List<Message> messages = new ArrayList<>();
        
        // 系统消息
        messages.add(new SystemMessage(systemPrompt));
        
        // 添加记忆上下文
        if (!memories.isEmpty()) {
            StringBuilder memoryContext = new StringBuilder("相关记忆：\n");
            for (String memory : memories) {
                memoryContext.append("- ").append(memory).append("\n");
            }
            messages.add(new SystemMessage(memoryContext.toString()));
        }
        
        // 用户消息
        messages.add(new UserMessage(userText));
        
        return messages;
    }

    /**
     * 生成备用响应
     */
    private String generateFallbackResponse(ChatRequest request) {
        PersonaConfig persona = personaService.getActivePersona(request.getUserId());
        
        switch (persona.getId()) {
            case "doctor":
                return "抱歉，我现在无法为您提供详细的医疗建议。建议您咨询专业医生。";
            case "chef":
                return "抱歉，我现在无法为您提供烹饪建议。请稍后再试。";
            case "companion":
                return "我现在有些困惑，但我会一直陪伴在您身边。请告诉我更多您的想法。";
            default:
                return "抱歉，我现在无法理解您的问题。请稍后再试。";
        }
    }

    /**
     * 生成个性化响应
     * 根据人格特质调整响应风格
     */
    public String personalizeResponse(String baseResponse, PersonaConfig persona) {
        Map<String, Object> traits = persona.getTraits();
        if (traits == null) {
            return baseResponse;
        }
        
        StringBuilder personalizedResponse = new StringBuilder(baseResponse);
        
        // 根据幽默程度添加表情符号
        if (traits.containsKey("humorLevel")) {
            double humorLevel = (Double) traits.get("humorLevel");
            if (humorLevel > 0.7) {
                personalizedResponse.append(" 😊");
            }
        }
        
        // 根据同理心程度添加关怀语句
        if (traits.containsKey("empathyLevel")) {
            double empathyLevel = (Double) traits.get("empathyLevel");
            if (empathyLevel > 0.8) {
                personalizedResponse.append("\n\n希望这能帮助到您。如果您还有其他问题，随时告诉我。");
            }
        }
        
        return personalizedResponse.toString();
    }
}